#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/4/15 15:28
# @Author  : Chenmm
# @File    : SysRole.py
# @Software: PyCharm

from app import db
from datetime import datetime
from .SysMenu import SysMenu





class SysRoleMenu(db.Model):
    __tablename__ = 'sys_role_menu'

    role_id = db.Column(
        db.BigInteger,
        db.ForeignKey('sys_role.id'),  # 添加外键指向 sys_role.id
        primary_key=True,
        comment='角色ID'
    )
    menu_id = db.Column(
        db.BigInteger,
        db.ForeignKey('sys_menu.id'),  # 添加外键指向 sys_menu.id
        primary_key=True,
        comment='菜单ID'
    )

    __table_args__ = (
        db.UniqueConstraint('role_id', 'menu_id', name='uk_roleid_menuid'),
        {'comment': '角色和菜单关联表'}
    )



class SysRole(db.Model):
    __tablename__ = 'sys_role'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    name = db.Column(db.String(64), nullable=False, comment='角色名称')
    code = db.Column(db.String(32), nullable=False, comment='角色编码')
    sort = db.Column(db.Integer, comment='显示顺序')
    status = db.Column(db.SmallInteger, default=1, comment='角色状态')
    data_scope = db.Column(db.SmallInteger, comment='数据权限')
    create_by = db.Column(db.BigInteger, comment='创建人ID')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_by = db.Column(db.BigInteger, comment='更新人ID')
    update_time = db.Column(db.DateTime, onupdate=datetime.now, comment='更新时间')
    is_deleted = db.Column(db.SmallInteger, default=0, comment='逻辑删除标识')

    menus = db.relationship(
        'SysMenu',
        secondary='sys_role_menu',  # 指定中间表
        backref=db.backref('roles', lazy='dynamic')  # 定义反向引用
    )

    __table_args__ = (
        db.UniqueConstraint('name', name='uk_name'),
        db.UniqueConstraint('code', name='uk_code'),
        {'comment': '角色表'}
    )

    def to_option_json(self):
        option = {
            'value': self.id,
            'label': self.name,
        }

        return option

    def to_pageination_dict(self):
        role = {
            "id": self.id,
            "name": self.name,
            "code": self.code,
            "status": self.status,
            "sort": self.sort,
            "createTime": self.create_time,
            "updateTime": self.update_time
        }
        return role
